/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package doc2db.interfaces.autent;

import doc2db.Keey;
import doc2db.Launcher;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileWorker;
import doc2db.interfaces.mainWindow.action.MyMouseListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author yuriy
 */
public class AutentFrame extends JFrame implements ActionListener{
    private JLabel Luser =  new JLabel("Системный псевдоним:");
    private JLabel Lpswd =  new JLabel("Системный пароль:   ");
    private JTextField user = new JTextField(20);
    private JPasswordField pswd =  new JPasswordField(20);
    private JButton okButton = new JButton("<html><p color=green>✓");
    private JButton cancelButton = new JButton("<html><p color=red>✗");
    private JButton newUsrButton = new JButton("<html><p color=blue><small>new");

    private String picturePath [] =  {
                FileBeginer.resurse_resurseFolderPane+Keey.sp+"button_cancel.png",  //✗
                FileBeginer.resurse_resurseFolderPane+Keey.sp+"button_ok.png"       //✓
    };

    private JPanel p;

    

   public AutentFrame(String u, String p) {
        initComponents();
        pswd.setText(p);
       if (u.equals("")) {
           user.setText(System.getProperty("user.name"));
       } else {
           user.setText(u);
            String pasStr = new String(pswd.getPassword());//pswd.getText();
           if(! pasStr.equals("")){
               this.actionPerformed(null);
           }
       }

    }

   /**
     * инициализирует компоненты
     * init all component
     */
    private void initComponents()  {
        FramePropertis();
        setVariableAction();
        Container contentPane = getContentPane();
        p = new JPanel(new BorderLayout());
        this.intiVariable();
        contentPane.add(p);
        try {
            //setIconImage(ImageIO.read(new File(Keey.imgPath + "main.jpg")));
            setIconImage(((ImageIcon) Launcher.getIcon("pane/submit.png")).getImage());
        } catch (Exception ex) {
            if (Keey.debug) {
                System.err.println("Can init window image :" + ex);
            }
        }

    }

    /**
     * создаёт окно по середине экрана с параметрами 255:330
     * create window in center of scren with paraneters 255:330
     *
     * @throws java.awt.HeadlessException
     */
    private void FramePropertis() throws HeadlessException {
        setTitle("doc2db autentification");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);
        setSize(400, 144);
        setLocationRelativeTo(null);
        setMinimumSize(getSize());
    }

    /**
     *
     * @return
     * @throws java.awt.HeadlessException
     * @throws java.io.IOException
     */
    private void intiVariable(){
        this.setVariableSize();

        Box u = Box.createHorizontalBox();
        u.add(Box.createHorizontalStrut(10));
        u.add(Luser);
        u.add(Box.createHorizontalStrut(10));
        u.add(user);
        u.add(Box.createHorizontalStrut(10));

        Box p2 = Box.createHorizontalBox();
        p2.add(Box.createHorizontalStrut(10));
        p2.add(Lpswd);
        p2.add(Box.createHorizontalStrut(10));
        p2.add(pswd);
        p2.add(Box.createHorizontalStrut(10));

        Box b1 = Box.createHorizontalBox();
        b1.add(Box.createHorizontalStrut(4));
        b1.add(cancelButton);
        b1.add(Box.createGlue());
        b1.add(newUsrButton);
        b1.add(Box.createGlue());
        b1.add(okButton);
        b1.add(Box.createHorizontalStrut(4));

        Box vb = Box.createVerticalBox();
        vb.add(Box.createVerticalStrut(10));
        vb.add(u);
        vb.add(Box.createVerticalStrut(10));
        vb.add(p2);
        vb.add(Box.createVerticalStrut(10));

        p.add(vb, BorderLayout.CENTER);
        p.add(b1, BorderLayout.SOUTH);

    }

    /**
     * определяем действия происходящие при выборе определённых переменных
     */
    private void setVariableAction() {
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.exit(1);
            }
        });
        NewUserAction f = new NewUserAction(this);
        newUsrButton.addActionListener(f);

        okButton.addActionListener(this);
        pswd.addActionListener(this);
        user.addActionListener(this);
    }

    /**
     * определяем визуальный резмер переменных на экране
     */
    private void setVariableSize() {
        Luser.setMaximumSize(new Dimension(800, 30));
        Lpswd.setMaximumSize(new Dimension(800, 30));
        user.setMaximumSize(new Dimension(800, 30));
        pswd.setMaximumSize(new Dimension(800, 30));
        okButton.setPreferredSize(new Dimension(29, 29));
        cancelButton.setPreferredSize(new Dimension(29, 29));
        newUsrButton.setPreferredSize(new Dimension(40, 22));
        okButton.setMaximumSize(okButton.getPreferredSize());
        cancelButton.setMaximumSize(cancelButton.getPreferredSize());
        newUsrButton.setMaximumSize(newUsrButton.getPreferredSize());
        Luser.setFont(UserProp.paneFont);
        Lpswd.setFont(UserProp.paneFont);
        user.setFont(UserProp.paneFont);
        pswd.setFont(UserProp.paneFont);
        okButton.setFont(UserProp.paneFont);
        cancelButton.setFont(UserProp.paneFont);
        newUsrButton.setFont(UserProp.paneFont);
        newUsrButton.setFocusCycleRoot(true);

        okButton.setForeground(Color.BLACK);
        //okButton.setBackground(Keey.buttonColor);
        cancelButton.setForeground(Color.BLACK);
        //cancelButton.setBackground(Keey.buttonColor);
        newUsrButton.setForeground(Color.BLACK);
        //newUsrButton.setBackground(Keey.buttonColor);
        newUsrButton.setToolTipText("<html><body  bgcolor=yellow><h4 color=black>" +
                "Создание нового пользователя");

        cancelButton.setIcon(new ImageIcon(picturePath[0]));
        okButton.setIcon(new ImageIcon(picturePath[1]));

        MouseListener rbl = new MyMouseListener();
        okButton.setContentAreaFilled(false);
        okButton.addMouseListener(rbl);
        cancelButton.setContentAreaFilled(false);
        cancelButton.addMouseListener(rbl);
        newUsrButton.setContentAreaFilled(false);
        newUsrButton.addMouseListener(rbl);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        String pasStr = new String(pswd.getPassword());//pswd.getText();
        String userStr = user.getText();
        String usrs = FileBeginer.resurse_users_usersFolder + Keey.sp + FileBeginer.useListName;

        if(Keey.decodStr(pasStr).equals(FileWorker.howInit(usrs,userStr))){
            UserProp.user = "" + userStr;
            UserProp.pswd = "" + pasStr;
            Keey.isAutentComplete = true;
        }else{
            JOptionPane.showMessageDialog(null, "Неверный пароль"
                    , "error! ",JOptionPane.ERROR_MESSAGE);
            this.setVisible(true);
        }

    }

}
